package net.dopan.pigframe.demo.controller;

import com.google.gson.Gson;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import net.dopan.pigframe.core.base.controller.response.ResponseBean;
import net.dopan.pigframe.core.utils.SymbolsUtils;
import net.dopan.pigframe.demo.mapper.UserActivityMapper;
import net.dopan.pigframe.demo.model.entity.UserActivity;
import net.dopan.pigframe.demo.model.entity.UserActivityParticipant;
import net.dopan.pigframe.demo.model.entity.UserActivityTime;
import net.dopan.pigframe.demo.model.entity.vo.PublishNoteTagVo;
import net.dopan.pigframe.demo.model.entity.vo.UserActivityBo;
import net.dopan.pigframe.demo.model.entity.vo.UserEventVo;
import net.dopan.pigframe.demo.model.entity.vo.UserNoteVo;
import net.dopan.pigframe.demo.service.*;
import net.dopan.pigframe.demo.service.ribbon.OssServerRibbon;
import net.dopan.pigframe.demo.service.ribbon.UserServiceRibbon;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.FileNameMap;
import java.net.URLConnection;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author wufeihong 发布活动
 */
@Controller
@RequestMapping("/addUserActivity")
@Slf4j
public class AddUserActivityController {

    @Autowired
    private ActivityClassifyService classifyService;
    @Autowired
    private UserNoteService userNoteService;
    @Autowired
    private UserActivityMapper userActivityMapper;

    @Autowired
    private HttpServletResponse response;
    //    @Qualifier("OSSServiceFallback")
//    @Autowired
//    private OSSServiceApi ossServiceApi;
    @Autowired
    private OssServerRibbon ossServerRibbon;
    @Autowired
    private UserActivityService userActivityService;
    @Autowired
    private UserServiceRibbon userServiceRibbon;
    @Autowired
    private UserActivityTimeService userActivityTimeService;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private UserActivityParticipantService userActivityParticipantService;

    /**
     * 获取用户身份验证 0未通过 1通过
     */
    @GetMapping("/getIdentityVerification")
    @ResponseBody
    @ApiOperation(value = "查询用户身份验证", notes = "查询用户身份验证")
    public ResponseBean getIdentityVerification(@RequestParam(value = "userId", required = false) String userId) {
        /** 允许该域发起跨域请求 */
        response.setHeader("Access-Control-Allow-Origin", "*");
        /**  允许的外域请求方式 */
        response.setHeader("Access-Control-Allow-Methods", "POST, GET");
//        String identityVerification = userServiceRibbon.getIdentityVerification(userId);
//        JSONObject obj = JSONObject.fromObject(identityVerification);
//        if (Integer.parseInt(obj.get("data") + "") == 1) {
//            return new ResponseBean(ResponseBean.SUCCESS, "已验证!", "");
//        }
        if (userActivityService.getIdentityVerification(userId) == 1) {
            return new ResponseBean(ResponseBean.SUCCESS, "已验证!", "");
        }
        return new ResponseBean(ResponseBean.FAIL, "请先验证身份!", "");
    }

    /**
     * 获取活动类型
     */
    @GetMapping("/getActivityClassify")
    @ResponseBody
    @ApiOperation(value = "获取活动类型", notes = "获取活动类型")
    public ResponseBean getActivityClassify() {
        /** 允许该域发起跨域请求 */
        response.setHeader("Access-Control-Allow-Origin", "*");
        /**  允许的外域请求方式 */
        response.setHeader("Access-Control-Allow-Methods", "POST, GET");
        return new ResponseBean<>(ResponseBean.SUCCESS, "", classifyService.findAll());
    }

    /**
     * 发起活动
     */
    @Transactional
    @PostMapping("/addUserActivity")
    @ResponseBody
    @ApiOperation(value = "发布活动(日期格式为yyyy.MM.dd HH:mm-HH:mm)", notes = "发起活动")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "activityName", value = "活动名称", required = true, dataType = "String"),
            @ApiImplicitParam(name = "activityId", value = "活动Id(有是编辑活动,无是发起活动)", required = false, dataType = "String")
    })
    public ResponseBean launch(UserActivityBo userActivityBo, @RequestParam("photo") MultipartFile photo, @RequestParam("html") MultipartFile html) {
        /** 允许该域发起跨域请求 */
        response.setHeader("Access-Control-Allow-Origin", "*");
        /**  允许的外域请求方式 */
        response.setHeader("Access-Control-Allow-Methods", "POST, GET");
        if (userActivityBo.getDateList().isEmpty()) {
            return new ResponseBean(ResponseBean.FAIL, "请填写活动日期！", "");
        }
        int activity_id;
        /** 发起活动为true 编辑活动为false */
        boolean flag = true;
        if (userActivityBo.getActivityId() == null) {
            /** 新建活动 */
            activity_id = userActivityService.findMaxId() == null ? 1 : userActivityService.findMaxId() + 1;
            /** 活动发起者默认为活动的参与者 */
            UserActivityParticipant userActivityParticipant = new UserActivityParticipant();
            userActivityParticipant.setUserId((int) userActivityBo.getUserId());
            userActivityParticipant.setActivityId(activity_id);
            userActivityParticipantService.insert(userActivityParticipant);

        } else {
            /** 编辑活动 */
            activity_id = Integer.parseInt(userActivityBo.getActivityId());
            /** 删除该活动时间列表 */
            userActivityTimeService.delUserActivityTime(userActivityBo.getActivityId());
            flag = false;
        }
        UserActivity userActivity = new UserActivity();
        BeanUtils.copyProperties(userActivityBo, userActivity);
        //上传html到服务器
//        String url = FileUtils.uploadImage(request, html);
        StringBuilder htmlUrl = new StringBuilder();
        htmlUrl.append("https://activityplatform.oss-cn-hangzhou.aliyuncs.com/");
        try {
            String str = ossServerRibbon.upload(html, request);
            System.err.println(str);
            Gson gson = new Gson();
            Map<String, Object> map = new HashMap<String, Object>();
            map = gson.fromJson(str, map.getClass());
            htmlUrl.append((String) map.get("data"));
        } catch (IOException e) {
            e.printStackTrace();
        }
        userActivity.setActivityDetail(htmlUrl.toString());
        //上传图片到服务器
//        String photoUrl = FileUtils.uploadImage(request, photo);
        StringBuilder photoUrl = new StringBuilder();
        photoUrl.append("https://activityplatform.oss-cn-hangzhou.aliyuncs.com/");
        try {
            String str = ossServerRibbon.upload(photo, request);
            System.err.println(str);
            Gson gson = new Gson();
            Map<String, Object> map = new HashMap<String, Object>();
            map = gson.fromJson(str, map.getClass());
            photoUrl.append((String) map.get("data"));
        } catch (IOException e) {
            e.printStackTrace();
        }
        userActivity.setCoverPhotoUrl(photoUrl.toString());

        userActivity.setActivityId(activity_id);
        userActivityService.addUserActivity(userActivity, flag);

        //   SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd HH:mm");

        /** 保存活动时间列表*/
        if (!userActivityBo.getDateList().isEmpty()) {
            for (String str : userActivityBo.getDateList()
            ) {
                UserActivityTime userActivityTime = new UserActivityTime();

                String[] strings = str.split("-");

                userActivityTime.setDateTimeStr(str);
                try {
                    String strings1 = str.substring(0, 10);
                    Date date = sdf.parse(strings1 + " " + strings[1]);
                    userActivityTime.setDateTime(date);
                } catch (ParseException e) {
                    e.printStackTrace();
                    return new ResponseBean(ResponseBean.FAIL, "日期格式为yyyy.MM.dd HH:mm-HH:mm", "");
                } catch (StringIndexOutOfBoundsException e) {
                    e.printStackTrace();
                    return new ResponseBean(ResponseBean.FAIL, "日期格式为yyyy.MM.dd HH:mm-HH:mm", "");
                }
                userActivityTime.setActivityId(activity_id);
                userActivityTimeService.addUserActivityTime(userActivityTime);
            }
        }
        return new ResponseBean(ResponseBean.SUCCESS, "提交活动成功", "");
    }

    /**
     * 发布笔记
     */
    @Transactional
    @PostMapping(value = "/addUserNote")
    @ResponseBody
    @ApiOperation(value = "发布笔记(限制@好友数量和添加的标签数量)", notes = "用postman测试！")
    public ResponseBean addUserNote(UserNoteVo userNoteVo, @RequestParam("files") MultipartFile[] files) {
        /** 允许该域发起跨域请求 */
        response.setHeader("Access-Control-Allow-Origin", "*");
        /**  允许的外域请求方式 */
        response.setHeader("Access-Control-Allow-Methods", "POST, GET");
        int noteId = userNoteService.findUserNoteMaxId() == null ? 1 : userNoteService.findUserNoteMaxId() + 1;

        for (MultipartFile file : files
        ) {
            getMimeType(file.getOriginalFilename());
            System.err.println(getMimeType(file.getOriginalFilename()));
            /**上传图片到服务器*/
//            String photoUrl = FileUtils.uploadImage(request, file);
            StringBuilder photoUrl = new StringBuilder();
            photoUrl.append("https://activityplatform.oss-cn-hangzhou.aliyuncs.com/");
            try {
                String str = ossServerRibbon.upload(file, request);
                System.err.println(str);
                Gson gson = new Gson();
                Map<String, Object> map = new HashMap<String, Object>();
                map = gson.fromJson(str, map.getClass());
                photoUrl.append((String) map.get("data"));
            } catch (IOException e) {
                e.printStackTrace();
            }
            userNoteService.addUserNotePhoto(String.valueOf(noteId), photoUrl.toString());
        }

        List<String> userIds = userNoteVo.getUserNoteMentionUserIds();
        List<String> tagIds = userNoteVo.getUserNoteTagIds();
        /** 发布笔记 */
        userNoteVo.setNoteId(String.valueOf(noteId));
        Date date = new Date();
        userNoteVo.setCreateTime(date);
        userNoteService.addUserNote(userNoteVo);
        if (userIds != null) {
            for (String str : userIds
            ) {
                /** 添加笔记@的好友*/
                userNoteService.addUserNoteMentionUser(str, String.valueOf(noteId));
            }
        }
        if (tagIds != null) {
            for (String str : tagIds
            ) {
                /** 添加笔记用到的标签*/
                userNoteService.addUserNoteTags(String.valueOf(noteId), str);
            }
        }
        return new ResponseBean(ResponseBean.SUCCESS, "发布成功!", "");
    }

    /**
     * 转发 笔记
     */
    @Transactional
    @GetMapping(value = "/shareUserNote")
    @ResponseBody
    @ApiOperation(value = "转发笔记或活动")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "user_id", value = "当前用户id", required = true, dataType = "String"),
            @ApiImplicitParam(name = "id", value = "活动或笔记id", required = true, dataType = "String"),
            @ApiImplicitParam(name = "type_flag", value = "转发类型 活动为1笔记2", required = true, dataType = "String")
    })
    public ResponseBean shareUserNote(@RequestParam("id") String id, @RequestParam("type_flag") String typeFlag, @RequestParam("user_id") String userId) {
        /** 允许该域发起跨域请求 */
        response.setHeader("Access-Control-Allow-Origin", "*");
        /**  允许的外域请求方式 */
        response.setHeader("Access-Control-Allow-Methods", "POST, GET");
        /** 转发活动 */
        if (typeFlag.equals("1")) {
            UserEventVo userEventVo = new UserEventVo();
            userEventVo.setCreateTime(new Date());
            userEventVo.setEventMsgId(Long.parseLong(id));
            userEventVo.setEventTypeId(3);
            userEventVo.setUserId(Long.parseLong(userId));
            userActivityMapper.addUserEvent(userEventVo);
        }
        /** 转发笔记 */
        else if (typeFlag.equals("2")) {
            UserEventVo userEventVo = new UserEventVo();
            userEventVo.setCreateTime(new Date());
            userEventVo.setEventMsgId(Long.parseLong(id));
            userEventVo.setEventTypeId(4);
            userEventVo.setUserId(Long.parseLong(userId));
            userActivityMapper.addUserEvent(userEventVo);
        }
        return new ResponseBean(ResponseBean.SUCCESS, "转发成功!", "");
    }

    @GetMapping("/addPublishNoteTag")
    @ResponseBody
    @ApiOperation(value = "添加笔记标签", notes = "添加笔记标签")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "tagName", value = "标签名称", required = true, dataType = "String"),
            @ApiImplicitParam(name = "userId", value = "添加标签的用户Id", required = true, dataType = "String")
    })
    public ResponseBean postPublishNoteTag(@RequestParam("tagName") String tagName, @RequestParam("userId") String userId) {
        /** 允许该域发起跨域请求 */
        response.setHeader("Access-Control-Allow-Origin", "*");
        /**  允许的外域请求方式 */
        response.setHeader("Access-Control-Allow-Methods", "POST, GET");
        /**
         * 验证标签名，支持中英文（包括全角字符）、数字、下划线和减号 （全角及汉字算两位）,长度为1-15位,中文按二位计数
         *
         */
        if (SymbolsUtils.validateUserName(tagName)) {
            PublishNoteTagVo publishNoteTag = new PublishNoteTagVo();
            publishNoteTag.setNoteTagName(tagName);
            publishNoteTag.setUserId(userId);
            publishNoteTag.setForbidden(0);
            userNoteService.addUserNoteTag(publishNoteTag);
            return new ResponseBean(ResponseBean.SUCCESS, "添加标签成功!", "");
        }
        return new ResponseBean(ResponseBean.FAIL, "请输入中英文 1-7位!", "");
    }

    @GetMapping("/getNoteTagList")
    @ResponseBody
    @ApiOperation(value = "模糊匹配笔记标签", notes = "模糊匹配笔记标签")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "tagName", value = "标签名称", required = true, dataType = "String")})
    public ResponseBean getPublishNoteList(@RequestParam("tagName") String tagName) {
        /** 允许该域发起跨域请求 */
        response.setHeader("Access-Control-Allow-Origin", "*");
        /**  允许的外域请求方式 */
        response.setHeader("Access-Control-Allow-Methods", "POST, GET");
        return new ResponseBean(ResponseBean.SUCCESS, "", userNoteService.getPublishNoteList(tagName));
    }

    public String getMimeType(String fileName) {
        FileNameMap fileNameMap = URLConnection.getFileNameMap();
        String type = fileNameMap.getContentTypeFor(fileName);
        System.err.println(type);
        return type;
    }


}
